import configparser
import os
import threading
import pytest
import time
from selenium import webdriver
from utils.read_files_tools.clean_files import del_file
from commons.get_path import ensure_path_sep, root_path
from utils.config.read_ini import get_url
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import IEDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from utils.config.write_ini import writ

config = configparser.ConfigParser()
config_path = os.path.join(root_path(), "config.ini")
config.read(config_path, encoding="utf-8")


# 会话前链接谷歌，窗口最大化/会话后关闭窗口
@pytest.fixture(scope='session')
def driver():
    # if 'browserType' in config.sections():
    #     config.remove_section('browserType')
    #     config.add_section('browserType')
    #     browser = input("请输入执行测试的浏览器：")
    #     config.set('browserType', 'browserName', browser)
    #
    config.set('DEFAULT', 'url', 'https://%(c)s.whgxwl.com/YX_kVc2yo2cmw0U/')
    if 'testServer' in config.sections():
        config.remove_section('testServer')
        config.add_section('testServer')
        config.remove_option('testServer', 'c')
    _url = input("请输入测试的站点：")
    config.set('testServer', 'c', _url)
    writ()

    # browser = config.get('browserType', 'browserName')
    browser = input("请输入执行测试的浏览器：")
    if browser == 'Firefox' or browser == 'firefox' or browser == '火狐':
        driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
    elif browser == 'Ie' or browser == 'ie':
        driver = webdriver.Ie(IEDriverManager().install())
    elif browser == 'Edge':
        driver = webdriver.Edge(EdgeChromiumDriverManager().install())
        return driver
    elif browser == 'Chrome' or browser == 'chrome' or browser == '谷歌':
        driver = webdriver.Chrome(ChromeDriverManager().install())
    # 隐藏浏览器界面
    # chrome_option = Options()
    # chrome_option.add_argument('--headless')
    # chrome_option.add_argument('--disable-gpu')
    # driver = webdriver.Chrome(options=chrome_option)
    # 自动下载浏览器对应版本的驱动

    # driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get(get_url())
    yield driver
    driver.quit()
    print(dir(driver))


# def run_case(name):
#     thread_list = []
#     thread = threading.Thread(target=driver, args=(name,))
#     thread_list.append(thread)
#     for j in thread_list:
#         j.start()


# 每条用例执行前等待元素加载完成
# @pytest.fixture(autouse=True)
# def wait(driver):
#     driver.implicitly_wait(1000)
#     yield
#     driver.implicitly_wait(1000)


def pytest_collection_modifyitems(items):
    """
    测试用例收集完成时，将收集到的 item 的 name 和 node_id 的中文显示在控制台上
    :return:
    """
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode_escape")
        item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")

    # 期望用例顺序
    # print("收集到的测试用例:%s" % items)
    appoint_items = ["test_get_user_info", "test_collect_addtool", "test_Cart_List", "test_ADD", "test_Guest_ADD",
                     "test_Clear_Cart_Item"]

    # 指定运行顺序
    run_items = []
    for i in appoint_items:
        for item in items:
            module_item = item.name.split("[")[0]
            if i == module_item:
                run_items.append(item)

    for i in run_items:
        run_index = run_items.index(i)
        items_index = items.index(i)

        if run_index != items_index:
            n_data = items[run_index]
            run_index = items.index(n_data)
            items[items_index], items[run_index] = items[run_index], items[items_index]


def pytest_terminal_summary(terminalreporter):
    """
    收集用例执行结果
    """
    _PASSED = len([i for i in terminalreporter.stats.get('passed', []) if i.when != 'teardown'])
    _ERROR = len([i for i in terminalreporter.stats.get('error', []) if i.when != 'teardown'])
    _FAILED = len([i for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown'])
    _SKIPPED = len([i for i in terminalreporter.stats.get('skipped', []) if i.when != 'teardown'])
    _TOTAL = terminalreporter._numcollected
    _TIMES = time.time() - terminalreporter._sessionstarttime
    print(f"用例总数: {_TOTAL}")
    print(f"异常用例数: {_ERROR}")
    print(f"失败用例数: {_FAILED}")
    print(f"跳过用例数: {_SKIPPED}")
    print("用例执行时长: %.2f" % _TIMES + " s")
    ("用例执行时长: %.2f" % _TIMES + " s")

    try:
        _RATE = _PASSED / _TOTAL * 100
        print("用例成功率: %.2f" % _RATE + " %")
    except ZeroDivisionError:
        print("用例成功率: 0.00 %")


@pytest.fixture(scope="session", autouse=False)
def clear_report():
    """如clean命名无法删除报告，这里手动删除"""
    del_file(ensure_path_sep("\\report"))

# # qq邮件
# if os.path.exists('send_dir.zip'):
#     os.system('del -s -q send_dir.zip')
# if os.path.exists('UI'):
#     os.system(r'rmdir /s /q UI')
#
# _Send_mail = SendEmail('send_dir.zip', r'report', r"send_dir.zip")
# _Send_mail.zipdir()
# _Send_mail.run()
